package cn.z2huo.algorithm.sort.data;

import cn.hutool.core.text.csv.CsvData;
import cn.hutool.core.text.csv.CsvReadConfig;
import cn.hutool.core.text.csv.CsvReader;
import cn.hutool.core.text.csv.CsvUtil;
import cn.hutool.core.util.StrUtil;
import cn.z2huo.algorithm.sort.entity.SortInputOutput;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.util.ResourceUtils;

import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

/**
 * <p>从测试 csv 文件中读取测试数据
 *
 * @author z2huo
 */
public class CsvTestDataInit {

    private static final String TEST_DATA_CLASS_PATH =
            ResourceUtils.CLASSPATH_URL_PREFIX + "csv/sort/";

    private static final String TEST_DATA_FILE_CLASS_PATH
            = ResourceUtils.CLASSPATH_URL_PREFIX + "csv/sort/test_data_1000.csv";
//            = ResourceUtils.CLASSPATH_URL_PREFIX + "csv/sort/test_data_10000.csv";
//            = ResourceUtils.CLASSPATH_URL_PREFIX + "csv/sort/test_data_100000.csv";
//            = ResourceUtils.CLASSPATH_URL_PREFIX + "csv/sort/test_data_1000000.csv";

    public List<SortInputOutput> getTestData() {
        return this.getTestData(1000);
    }

    public List<SortInputOutput> getTestData(int dataSize) {

        CsvReadConfig csvReadConfig = CsvReadConfig.defaultConfig();
        csvReadConfig.setBeginLineNo(0);

        String filePath = TEST_DATA_CLASS_PATH + "test_data_" + dataSize + ".csv";
        try (InputStreamReader fileReader = new FileReader(ResourceUtils.getFile(filePath));
             CsvReader reader = CsvUtil.getReader(fileReader, csvReadConfig);) {

            CsvData csvData = reader.read();

            List<SortInputOutput> list = csvData.getRows().stream()
                    .map(row -> new SortInputOutput(StrUtil.splitToInt(row.getFirst(), ';'),
                            StrUtil.splitToInt(row.getLast(), ';')))
                    .toList();

            boolean sortedFlag = list.stream().allMatch(sortInputOutput ->
                    ArrayUtils.isSorted(sortInputOutput.getResultArray()));
            if (!sortedFlag) {
                throw new RuntimeException("csv data result array is not sorted");
            }
            return list;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
